<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/19
 * Time: 17:42
 */

namespace app\backstage\logic;


use app\backstage\model\ManagerUser;
use app\common\model\Bookshelf;
use app\common\model\Novel;
use app\common\model\NovelChapter;
use app\common\model\QuickUser;
use app\common\model\Auditor;
use app\common\model\UserBlack;
use app\common\model\UserBookPoints;
use app\common\model\UserWhite;
use think\Db;

class UserLogic
{
    /*
     * 用户充值
     * */
    public function recharge($params)
    {

        $record = Db::table('quick_user')->where('id',$params['uid'])->field('id,vip_exp_time,book_coin,quick_id')->findOrEmpty();

        if(empty($record))
        {
            return ['code'=>102,'msg'=>'该用户不存在'];
        }

        $record['vip_exp_time'] = $record['vip_exp_time'] > 0 ? $record['vip_exp_time'] : 0;
        $vip_text = '普通会员';

        if($params['type'] == 2)
        {
            $date = date('Y-m-d');
            if($record['vip_exp_time'] < time())
            {
                if($params['vipdays'] < 0){
                    $vip_date = date("Y-m-d 23:59:59", strtotime($date . $params['vipdays'] . " day"));
                }else{
                    $vip_date = date("Y-m-d 23:59:59", strtotime($date . "+" . $params['vipdays'] . " day"));
                }

            }else{

                $date = date('Y-m-d H:i:s',$record['vip_exp_time']);

                if($params['vipdays'] < 0){
                    $vip_date = date("Y-m-d 23:59:59", strtotime($date . $params['vipdays'] . " day"));
                }else{
                    $vip_date = date("Y-m-d 23:59:59", strtotime($date . "+" . $params['vipdays'] . " day"));
                }

            }

            if(strtotime($vip_date) > time())
            {
                $vip_text = '<span style="color: #009688;">vip会员</span>';
            }
         
            $vip_exp_time = strtotime($vip_date);

            $res = Db::table('quick_user')->where('id',$params['uid'])->update(['vip_exp_time'=>$vip_exp_time]);
            $res2 = Db::table('quick_user_'.$record['quick_id'])->where('id',$params['uid'])->update(['vip_exp_time'=>$vip_exp_time]);
        }else{

            if($params['virtual_currency'] < 0)
            {
                $virtual_currency = abs($params['virtual_currency']);

                if($record['book_coin'] < $virtual_currency)
                {
                    return ['code'=>102,'msg'=>'用户书币余额不足，请重新输入书币金额'];
                }

                $res = Db::table('quick_user')->where('id',$params['uid'])->setDec('book_coin', $virtual_currency);
                $res2 = Db::table('quick_user_'.$record['quick_id'])->where('id',$params['uid'])->setDec('book_coin', $virtual_currency);
            }else{
                $res = Db::table('quick_user')->where('id',$params['uid'])->setInc('book_coin', $params['virtual_currency']);
                $res2 = Db::table('quick_user_'.$record['quick_id'])->where('id',$params['uid'])->setInc('book_coin', $params['virtual_currency']);
            }

        }

        if($res && $res2)
        {
            $book_coin = Db::table('quick_user')->where('id',$params['uid'])->value('book_coin');
            return ['code'=>100,'msg'=>'操作成功','data'=>['type'=>$params['type'],'vip_text'=>$vip_text,'book_coin'=>$book_coin]];
        }else{
            return ['code'=>102,'msg'=>'操作失败'];
        }
    }

    /**
     * 用户列表
     * @param $params
     * @return \think\response\Json
     * @Author: whh
     */
    public function userList($where, $page, $limit)
    {
        $orderBy = "id desc";
        $with = ['quickApp', 'channel', 'bookPoints', 'agent', 'sourceAgent', 'sourceChannel'];
        $list = QuickUser::getList($where, '*', $orderBy, $page, $limit, $with);
        $ubp = new UserBookPoints();

        foreach ($list as $k => $v) {
            $list[$k]['vip_text'] = $v->vip_text;
            $list[$k]['pay_money_text'] = $v->pay_money_text;
            $list[$k]['book_point'] = $ubp->getBalancePoint($v->id);
            $list[$k]['eb'] = null;
            if ($v->agent && $v->agent->parent_id) {
                $list[$k]['eb'] = ManagerUser::where('id', $v->agent->parent_id)->field("id,account")->findOrFail();
            }
            $list[$k]['source_eb'] = null;
            if ($v->source_agent && $v->source_agent->parent_id) {
                $list[$k]['source_eb'] = ManagerUser::where('id', $v->source_agent->parent_id)->field("id,account")->findOrFail();
            }
            $bsNid = Bookshelf::where("uid",$v->id)->order("read_time desc")->value('novel_id');
            if($bsNid){
                $list[$k]['last_novel'] = Db::table('novel')->where('id', $bsNid)->field('id,title')->find();
            }
        }
        $count = QuickUser::getCount($where);
        return sucJson($list, $count);
    }

    /**
     * 读者列表
     * @param $where
     * @param $readerType
     * @param $page
     * @param $limit
     * @return \think\response\Json
     * @Author: whh
     */
    public function readersList($where, $readerType, $page, $limit)
    {
        $role = request()->_role;
        $user = request()->_user;
        /**
         * 运营用户还是注册用户
         */
        if ($readerType == 'operate') {
            if ($role->alias == 'channel') {
                $where[] = ['channel_id', '=', $user->id];
            }
            if ($role->alias == 'agent') {
                $where[] = ['agent_id', '=', $user->id];
            }
            if ($role->alias == 'eb') {
                $userModel = new \app\backstage\model\ManagerUser();
                $agentIds = $userModel->sonUsersIds($user->id);
                $where[] = ['agent_id', 'in', $agentIds];
                $where[] = ['agent_id', '<>', 0];
            }
        } else {
            if ($role->alias == 'channel') {
                $where[] = ['source_channel_id', '=', $user->id];
            }
            if ($role->alias == 'agent') {
                $where[] = ['source_agent_id', '=', $user->id];
            }
            if ($role->alias == 'eb') {
                $userModel = new \app\backstage\model\ManagerUser();
                $channelIds = $userModel->sonUsersIds($user->id);
                $where[] = ['source_agent_id', 'in', $channelIds];
                $where[] = ['source_agent_id', '<>', 0];
            }
        }
        $orderBy = "id desc";
        $with = ['quickApp', 'bookPoints'];
        if ($role->alias == 'agent' || $role->alias == 'eb') {
            $with[] = 'channel';
            $with[] = 'sourceChannel';
            if ($role->alias == 'eb') {
                $with[] = 'agent';
                $with[] = 'sourceAgent';
            }
        }
        $field = "id,quick_id,channel_id,agent_id,source_agent_id,source_channel_id,source_novel_id,regdate,regtime,login_time,book_coin,vip_exp_time,pay_times,pay_money,provider,ip_addr";
        $list = QuickUser::getList($where, $field, $orderBy, $page, $limit, $with);
        $ubp = new UserBookPoints();
        foreach ($list as $k => $v) {
            $list[$k]['vip_text'] = $v->vip_text;
            $list[$k]['pay_money_text'] = $v->pay_money_text;
            $list[$k]['book_point'] = $ubp->getBalancePoint($v->id);
            $bsNid = Bookshelf::where("uid",$v->id)->order("read_time desc")->value('novel_id');
            if($bsNid){
                $list[$k]['last_novel'] = Db::table('novel')->where('id', $bsNid)->field('id,title')->find();
            }
            /**
             * 判断是否属于本人下属用户
             */
            if ($readerType == 'register') {
                $list[$k]['is_belong'] = 0;
                if ($role->alias == 'channel' && $v->channel_id == $user->id) {
                    $list[$k]['is_belong'] = 1;
                }
                if ($role->alias == 'agent' && $v->agent_id == $user->id) {
                    $list[$k]['is_belong'] = 1;
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $agentIds = $userModel->sonUsersIds($user->id);
                    if (in_array($v->agent_id, $agentIds)) {
                        $list[$k]['is_belong'] = 1;
                    }
                }
            } else {
                $list[$k]['is_register'] = 0;
                if ($role->alias == 'channel' && $v->source_channel_id == $user->id) {
                    $list[$k]['is_register'] = 1;
                }
                if ($role->alias == 'agent' && $v->source_agent_id == $user->id) {
                    $list[$k]['is_register'] = 1;
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $agentIds = $userModel->sonUsersIds($user->id);
                    if (in_array($v->source_agent_id, $agentIds)) {
                        $list[$k]['is_register'] = 1;
                    }
                }
            }
        }
        $count = QuickUser::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * 设置审核人员
     * @param $uid
     * @param $type
     * @param string $scene
     * @return \think\response\Json
     * @Author: whh
     */
    public function setReview($uid, $type, $scene = 'reception')
    {
        $model = new Auditor();
        $review = $model->where('uid', $uid)->find();
        if ($scene == 'backstage') {
            /*
             * 后端只能更改类型
             */
            if (!$review) {
                return errJson('数据异常');
            }
            $review->type = $type;
        }
        if ($scene == 'reception') {
            /*
             * 前端只能新增
             */
            $review->uid = $uid;
            $review->type = $type;
        }
        $review->save();
        return sucJson();
    }


    /**
     * @param $table_suffix
     * @param $type 1：添加 2：删除
     * @param $uid
     * @throws \Exception
     * @Author: whh
     */
    public function setBlackOrWhite($table_suffix, $type, $uid)
    {
        if ($table_suffix == 'black') {
            $model = new UserBlack();
            $user = QuickUser::get($uid);
            if ($user) {
                $flag = $model->where("userId", $user->device_id)->find();
                if (!$flag) {
                    $model->userId = $user->device_id;
                    $model->status = $type;
                    $model->save();
                }else{
                    $flag->status = $type;
                    $flag->save();
                }
            }
        } elseif ($table_suffix == 'white') {
            $model = new UserWhite();
            if ($type == 2) {
                $model->where('uid', $uid)->delete();
            } elseif ($type == 1) {
                $flag = $model->where('uid', $uid)->find();
                if (!$flag) {
                    $model->insert([
                        'uid' => $uid
                    ]);
                }
            }
        } else {
            die;
        }
    }


    /**
     * 读者阅读记录
     * @param $month
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     */
    public function readRecordDetailList($month, $where, $page, $limit)
    {
        $table = "quick_user_read_record_{$month}";
        $list = Db::table($table)->where($where)->order("id desc")->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $list[$k]['novel_title'] = Novel::where('id', $v['novel_id'])->value('title');
            $vWhere = [];
            $vWhere[] = ['novel_id', '=', $v['novel_id']];
            $vWhere[] = ['chapter_no', '=', $v['chapter_no']];
            $list[$k]['chapter_title'] = NovelChapter::where($vWhere)->value('name');
        }
        $count = Db::table($table)->where($where)->count();
        return sucJson($list, $count);
    }

    /**
     * 领取记录
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     */
    public function giveList($where, $page, $limit)
    {
        $list = UserBookPoints::getList($where, '*', "id desc", $page, $limit);
        foreach ($list as $k => $v) {
            $list[$k]['overdue_date'] = $v->overdue_date;
        }
        $count = UserBookPoints::getCount($where);
        return sucJson($list, $count);
    }
}